<?php

namespace app\index\controller;

use think\Controller;
use think\Request;
use think\Db;
use app\index\model\Goods as GoodsModel;
class Goods extends Controller
{
	public function query(){
		$goods = GoodsModel::select();
		// $goodsSku = $goods->GoodsSku;
		return json($goods);
	}
	public function queryGoodsCategory(){
		$goods = Db::query('select g.id as id,g.name as gName,c.name as cName from goods g left join category c on g.categoryId=c.id');
		return json($goods);
	}
	// 根据分类id查询商品
	public function findGoodsByCategoryId(){
		$categoryId = input('get.categoryId');
		$goods = GoodsModel::get(["categoryId"=>$categoryId]);
		return json($goods);
	}
	public function save(){
		$name = input('post.name');
		$categoryId = input('post.categoryId');
		$goods = new GoodsModel();
		$goods->name = $name;
		$goods->categoryId = $categoryId;
		$goods->save();
	}
	public function delete(){
		$id = input('get.id');
		$goods = goodsModel::get($id);
		$goods->delete();
	} 
	public function fQueryGoodsAndfirstSku(){
		$goods = Db::query("select id as gid,name as gName,goodsImg from goods");
		foreach($goods as $i=>$item){
			$r = Db::query('select name as sName,price from goodssku where goodsId=? limit 1',[$item['gid']]);
			$goods[$i]["sku"] = $r;
		}
		// $goods = Db::query('select gid,name as sName,gName,price,goodsImg from goodssku right join (select id as gid,name as gName,goodsImg from goods) g on g.gid = goodssku.goodsId');
		return json(["code"=>200,"data"=>$goods]);
	}
	public function fQueryGoodsAndfirstSkuByid(){
		$id = input('get.id');
		$goods = Db::query('select gid,name as sName,gName,price,goodsImg from goodssku right join (select id as gid,name as gName,goodsImg from goods where categoryId=?) g on g.gid = goodssku.goodsId',[$id]);
		return json(["code"=>200,"data"=>$goods]);
	}
	public function queryByid(){
		$id = input('get.id');
		$res = Db::query('select id as sid,name as sname,gname,price from goodssku right join 
		(select id as gid,name as gname from goods where id=?) g
		on goodssku.goodsId=g.gid',[$id]);
		foreach($res as $i=>$item){
			$r = Db::query('select img from goodsskuimg where goodsskuid=?',[$item['sid']]);
			$res[$i]['img'] = $r;
		}
		return json(["code"=>200,"data"=>$res]);
	}
	public function queryBysid(){
		$sid = input('get.sid');
		$res = Db::query('select * from goodssku where id=?',[$sid]);
		$skuimgres = Db::query('select img from goodsskuimg where goodsskuid=?',[$sid]);
		$goodres = Db::query('select * from goods where id=?',[$res[0]['goodsId']]);
		$res[0]['goods'] = $goodres;
		$res[0]['skuimg'] = $skuimgres;
		return json(["code"=>200,"data"=>$res]);
	}
}
